#!/bin/bash

# 用于自动生成代理配置信息

cd ${BASH_SOURCE%/*} 2>/dev/null

# 端口映射列表 # 服务内部名称:内部端口:外部访问端口
items=(
    hadoop-hdfs-nn:50070:50070
    hadoop-hdfs-dn-1:50075:50075
    hadoop-hdfs-dn-2:50075:50076
    hadoop-hdfs-dn-3:50075:50077
    hadoop-yarn-rm:8088:8088
    hadoop-yarn-nm:8042:8042
)

# 获取当前主机IP
get_lan_ip(){
    host_if=$(ip route | grep default | cut -d' ' -f5)
    ip addr | grep "$host_if$" | awk '{print $2}' | cut -d'/' -f1
}
LAN_IP=$(get_lan_ip | head -1)

# 默认代理配置
cat > Caddyfile <<EOF
:9180 {
    gzip
    browse
    log stdout
    errors stderr

    ext .md
    markdown
}
EOF

# 端口映射页面
cat > index.md <<EOF
+++
title = "Caddy Web Server"
+++

### Caddy web server custom build

Plugins:

* http.ipfilter
* http.prometheus

### 监控

**[portainer:9000](http://${LAN_IP}:9000)**

**[prometheus:9090](http://${LAN_IP}:9090)**

**[grafana:3000](http://${LAN_IP}:3000)**

### 服务web管理

EOF

# 循环列表
for item in ${items[@]}; do
    HOST=$(echo $item | cut -f1 -d ':')
    SPORT=$(echo $item | cut -f2 -d ':')
    DPORT=$(echo $item | cut -f3 -d ':')

    # 根据模板创建代理配置
    cat >> Caddyfile <<EOF

:$DPORT {
    # basicauth / {\$ADMIN_USER} {\$ADMIN_PASSWORD}
    proxy / $HOST:$SPORT {
            transparent
        }

    errors stderr
    tls off
}
EOF

    # 更改容器启动文件中的端口映射
    if [ ! "$(grep "$DPORT:$DPORT" caddy-compose.yml)" ]; then
        sed -i "/ports:/a\      - \"$DPORT:$DPORT\"" ./caddy-compose.yml
    fi

    if [ ! "$(grep "$DPORT:$DPORT" ./caddy.yml)" ]; then
        sed -i "/ports:/a\      - \"$DPORT:$DPORT\"" ./caddy.yml
    fi

    # 生成端口映射信息
    cat >> index.md <<EOF

**[$HOST:$SPORT](http://${LAN_IP}:${DPORT})**
EOF

done

if false; then

echo 'delete cluster_caddy.'
docker service rm cluster_caddy

sleep 5
echo 'Create cluster_caddy.'
docker stack deploy -c ./caddy-compose.yml cluster > /dev/null

sleep 2
docker stack ps cluster | grep caddy
docker service ls | grep caddy

fi
